<template>
	<view class="test-container">
		<!-- 顶部信息栏 -->
		<view class="top-bar" :style="{ paddingTop: safeDistance + 'px' }">
			<view class="back-button" @click="handleGoBack">
				<text class="back-icon">←</text>
			</view>
			<view class="progress-info">
				<text class="progress-text">{{ currentIndex + 1 }}/{{ questions.length }}</text>
			</view>
			<view class="timer">
				<text class="timer-icon">⏱</text>
				<text class="timer-text">{{ formatTime(timeUsed) }}</text>
			</view>
		</view>

		<!-- 进度条 -->
		<view class="progress-bar">
			<view class="progress-fill" :style="{ width: progressWidth + '%' }"></view>
		</view>

		<!-- 题目内容 -->
		<scroll-view class="question-scroll" scroll-y v-if="currentQuestion">
			<view class="question-card">
				<!-- 分类信息和题目类型标签 -->
				<view class="question-header">
					<!-- 分类信息 -->
					<view class="category-badge" v-if="getCategoryInfo(currentQuestion.category)">
						<text class="category-icon">{{ getCategoryInfo(currentQuestion.category)?.icon }}</text>
						<text class="category-name">{{ getCategoryInfo(currentQuestion.category)?.name }}</text>
					</view>

					<!-- 题目类型和难度标签 -->
					<view class="question-type">
						<view class="type-badge" :class="'type-' + currentQuestion.difficulty">
							<text class="type-text">{{ getTypeText(currentQuestion.type) }}</text>
						</view>
						<view class="difficulty-badge" :class="'diff-' + currentQuestion.difficulty">
							<text class="difficulty-text">{{ getDifficultyText(currentQuestion.difficulty) }}</text>
						</view>
					</view>
				</view>

				<!-- 题目标题 -->
				<text class="question-title">{{ currentQuestion.question }}</text>

				<!-- 代码示例（如果有） -->
				<view v-if="currentQuestion.code" class="code-block">
					<text class="code-text">{{ currentQuestion.code }}</text>
				</view>

				<!-- 选项列表 -->
				<view class="options-list">
					<view 
						v-for="option in currentQuestion.options" 
						:key="option.key"
						class="option-item"
						:class="{ 'option-selected': isSelected(option.key) }"
						@click="handleSelectOption(option.key)"
					>
						<view class="option-radio">
							<view class="radio-inner" v-if="isSelected(option.key)"></view>
						</view>
						<view class="option-content">
							<text class="option-key">{{ option.key }}.</text>
							<text class="option-text">{{ option.text }}</text>
						</view>
					</view>
				</view>

				<!-- 多选提示 -->
				<view v-if="currentQuestion.type === 'multiple'" class="multi-tip">
					<text class="tip-icon">💡</text>
					<text class="tip-text">本题为多选题，可选择多个选项</text>
				</view>

				<!-- 查看答案按钮 -->
				<view class="answer-section">
					<button 
						class="view-answer-btn" 
						@click="handleToggleAnswer"
						:class="{ 'answer-expanded': showAnswer }"
					>
						<text class="btn-icon">{{ showAnswer ? '▼' : '▶' }}</text>
						<text class="btn-text">{{ showAnswer ? '隐藏答案' : '查看答案' }}</text>
					</button>

					<!-- 答案展示区域 -->
					<view v-if="showAnswer" class="answer-content">
						<!-- 正确答案 -->
						<view class="answer-item">
							<text class="answer-label">正确答案：</text>
							<view class="answer-options">
								<text 
									v-for="(ansKey, index) in currentQuestion.answer" 
									:key="index"
									class="answer-key"
								>{{ ansKey }}</text>
							</view>
						</view>

						<!-- 答案解析 -->
						<view class="explanation-item" v-if="currentQuestion.explanation">
							<text class="explanation-label">解析：</text>
							<text class="explanation-text">{{ currentQuestion.explanation }}</text>
						</view>

						<!-- 代码示例（如果有） -->
						<view class="code-example" v-if="currentQuestion.code">
							<text class="code-label">代码示例：</text>
							<view class="code-block">
								<text class="code-text">{{ currentQuestion.code }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<button 
				class="nav-button prev-button" 
				@click="handlePrevQuestion"
				:disabled="currentIndex === 0"
			>
				<text class="button-text">上一题</text>
			</button>
			
			<button 
				v-if="currentIndex < questions.length - 1"
				class="nav-button next-button" 
				@click="handleNextQuestion"
			>
				<text class="button-text">下一题</text>
			</button>
			
			<button 
				v-else
				class="nav-button submit-button" 
				@click="handleSubmit"
			>
				<text class="button-text">提交答卷</text>
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onLoad, onUnload } from '@dcloudio/uni-app';
	import { ref, computed } from 'vue';
	import { getQuestionsByCategories, getExamChannelByTechId } from '@/services/exam';
	import { categories as categoryList } from '@/data/knowledge';
	import type { Question, UserAnswer, ExamChannel } from '@/types/exam';
	import type { Category } from '@/types/knowledge';

	// 测试通道信息
	const channelInfo = ref<ExamChannel | null>(null);
	
	// 技术ID和分类（字符串，用于传递参数）
	const techId = ref('');
	const categories = ref('');
	
	// 题目列表
	const questions = ref<Question[]>([]);
	
	// 当前题目索引
	const currentIndex = ref(0);
	
	// 用户答案记录
	const userAnswers = ref<Map<number, string[]>>(new Map());
	
	// 计时器
	const timeUsed = ref(0);
	let timer: number | null = null;
	
	// 是否显示答案
	const showAnswer = ref(false);

	// 安全距离（顶部内边距 = 安全区域 + 基础间距）
	const safeDistance = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		const safeAreaTop = systemInfo.safeAreaInsets?.top || 0;
		// 基础间距 20px（约等于 40rpx），加上安全区域
		return safeAreaTop + 20;
	});
	
	// 当前题目
	const currentQuestion = computed(() => {
		return questions.value[currentIndex.value];
	});
	
	// 进度百分比
	const progressWidth = computed(() => {
		if (questions.value.length === 0) return 0;
		return ((currentIndex.value + 1) / questions.value.length) * 100;
	});

	// 页面加载
	onLoad((options: any) => {
		techId.value = options.techId || '';
		categories.value = options.categories || '';
		
		if (!techId.value || !categories.value) {
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}

		// 获取通道信息
		channelInfo.value = getExamChannelByTechId(techId.value) || null;
		
		// 解析分类ID列表
		const categoryIds = categories.value.split(',').filter(id => id);
		
		// 根据分类加载题目
		questions.value = getQuestionsByCategories(techId.value, categoryIds);
		
		if (questions.value.length === 0) {
			uni.showToast({
				title: '暂无题目',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}

		// 开始计时
		startTimer();
	});

	// 页面卸载
	onUnload(() => {
		stopTimer();
	});

	// 开始计时
	const startTimer = () => {
		timer = setInterval(() => {
			timeUsed.value++;
		}, 1000) as unknown as number;
	};

	// 停止计时
	const stopTimer = () => {
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
	};

	// 格式化时间
	const formatTime = (seconds: number): string => {
		const mins = Math.floor(seconds / 60);
		const secs = seconds % 60;
		return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
	};

	// 判断选项是否被选中
	const isSelected = (key: string): boolean => {
		const questionId = currentQuestion.value?.id;
		if (!questionId) return false;
		const answer = userAnswers.value.get(questionId) || [];
		return answer.includes(key);
	};

	// 选择选项
	const handleSelectOption = (key: string) => {
		const question = currentQuestion.value;
		if (!question) return;

		const questionId = question.id;
		let answer = userAnswers.value.get(questionId) || [];

		if (question.type === 'single' || question.type === 'judge') {
			// 单选或判断题，替换答案
			answer = [key];
		} else if (question.type === 'multiple') {
			// 多选题，切换选中状态
			if (answer.includes(key)) {
				answer = answer.filter(k => k !== key);
			} else {
				answer = [...answer, key];
			}
		}

		userAnswers.value.set(questionId, answer);
	};

	// 上一题
	const handlePrevQuestion = () => {
		if (currentIndex.value > 0) {
			currentIndex.value--;
			showAnswer.value = false; // 切换题目时隐藏答案
		}
	};

	// 下一题
	const handleNextQuestion = () => {
		if (currentIndex.value < questions.value.length - 1) {
			currentIndex.value++;
			showAnswer.value = false; // 切换题目时隐藏答案
		}
	};

	// 切换答案显示
	const handleToggleAnswer = () => {
		showAnswer.value = !showAnswer.value;
	};

	// 获取题型文本
	const getTypeText = (type: string): string => {
		const typeMap: Record<string, string> = {
			single: '单选题',
			multiple: '多选题',
			judge: '判断题'
		};
		return typeMap[type] || '';
	};

	// 获取难度文本
	const getDifficultyText = (difficulty: string): string => {
		const diffMap: Record<string, string> = {
			easy: '简单',
			medium: '中等',
			hard: '困难'
		};
		return diffMap[difficulty] || '';
	};

	// 获取分类信息
	const getCategoryInfo = (categoryName: string): Category | undefined => {
		if (!categoryName) {
			return undefined;
		}
		if (!Array.isArray(categoryList) || categoryList.length === 0) {
			return undefined;
		}
		return categoryList.find(cat => cat.name === categoryName);
	};

	// 提交答卷
	const handleSubmit = () => {
		// 检查是否有未作答的题目
		const unansweredCount = questions.value.filter(q => {
			const answer = userAnswers.value.get(q.id);
			return !answer || answer.length === 0;
		}).length;

		if (unansweredCount > 0) {
			uni.showModal({
				title: '提示',
				content: `还有${unansweredCount}道题未作答，确认提交吗？`,
				success: (res) => {
					if (res.confirm) {
						submitExam();
					}
				}
			});
		} else {
			submitExam();
		}
	};

	// 提交测试
	const submitExam = () => {
		stopTimer();

		// 计算成绩
		let correctCount = 0;
		const answerRecords: UserAnswer[] = [];

		questions.value.forEach(question => {
			const userAnswer = userAnswers.value.get(question.id) || [];
			const isCorrect = checkAnswer(userAnswer, question.answer);
			
			if (isCorrect) {
				correctCount++;
			}

			answerRecords.push({
				questionId: question.id,
				userAnswer,
				isCorrect,
				timeUsed: 0
			});
		});

		const totalCount = questions.value.length;
		const score = Math.round((correctCount / totalCount) * 100);
		const accuracy = Math.round((correctCount / totalCount) * 100);

		// 跳转到结果页
		uni.redirectTo({
			url: `/pages/exam/result?score=${score}&correctCount=${correctCount}&totalCount=${totalCount}&accuracy=${accuracy}&timeUsed=${timeUsed.value}&techId=${techId.value}&categories=${categories.value}`
		});
	};

	// 检查答案是否正确
	const checkAnswer = (userAnswer: string[], correctAnswer: string[]): boolean => {
		if (userAnswer.length !== correctAnswer.length) return false;
		const sortedUser = [...userAnswer].sort();
		const sortedCorrect = [...correctAnswer].sort();
		return sortedUser.every((val, index) => val === sortedCorrect[index]);
	};

	// 返回上一页
	const handleGoBack = () => {
		uni.showModal({
			title: '确认返回',
			content: '返回后当前答题记录将不会保存，确认返回吗？',
			success: (res) => {
				if (res.confirm) {
					stopTimer();
					uni.navigateBack();
				}
			}
		});
	};
</script>

<style lang="scss" scoped>
	.test-container {
		height: 100vh;
		background: linear-gradient(180deg, #f5f7fa 0%, #e9ecef 100%);
		display: flex;
		flex-direction: column;
		overflow: hidden;
		position: relative;
	}

	/**
	 * 顶部信息栏
	 */
	.top-bar {
		flex-shrink: 0;
		padding-left: 32rpx;
		padding-right: 32rpx;
		padding-bottom: 20rpx;
		background: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
		position: relative;
		z-index: 10;
		gap: 20rpx;
		box-sizing: border-box;
	}

	.back-button {
		width: 72rpx;
		height: 72rpx;
		background: white;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
		transition: all 0.3s ease;
		flex-shrink: 0;

		&:active {
			transform: scale(0.92);
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
		}
	}

	.back-icon {
		font-size: 44rpx;
		color: #2c3e50;
		font-weight: 700;
	}

	.progress-info {
		flex: 1;
	}

	.progress-text {
		font-size: 32rpx;
		font-weight: 800;
		color: #667eea;
	}

	.timer {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 12rpx 20rpx;
		background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
		border-radius: 100rpx;
	}

	.timer-icon {
		font-size: 28rpx;
	}

	.timer-text {
		font-size: 28rpx;
		font-weight: 700;
		color: #1a202c;
	}

	/**
	 * 进度条
	 */
	.progress-bar {
		height: 6rpx;
		background: #e9ecef;
		position: relative;
		z-index: 9;
	}

	.progress-fill {
		height: 100%;
		background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
		transition: width 0.3s ease;
	}

	/**
	 * 题目滚动区域
	 */
	.question-scroll {
		flex: 1;
		padding: 24rpx;
		overflow-y: auto;
		box-sizing: border-box;
	}

	.question-card {
		background: white;
		border-radius: 24rpx;
		padding: 32rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		display: flex;
		flex-direction: column;
		margin-bottom: 24rpx;
	}

	/**
	 * 题目头部（分类和类型标签）
	 */
	.question-header {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 24rpx;
		flex-wrap: wrap;
	}

	/**
	 * 分类标签
	 */
	.category-badge {
		display: flex;
		align-items: center;
		gap: 10rpx;
		padding: 14rpx 24rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 50rpx;
		box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.35);
		transition: all 0.3s ease;
		flex-shrink: 0;
		
		&:hover {
			transform: translateY(-2rpx);
			box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.4);
		}
	}

	.category-icon {
		font-size: 36rpx;
		line-height: 1;
		display: block;
	}

	.category-name {
		font-size: 28rpx;
		font-weight: 800;
		color: white;
		letter-spacing: 1rpx;
	}

	/**
	 * 题目类型标签
	 */
	.question-type {
		display: flex;
		gap: 12rpx;
		flex-shrink: 0;
	}

	.type-badge, .difficulty-badge {
		padding: 8rpx 16rpx;
		border-radius: 10rpx;
	}

	.type-easy { background: linear-gradient(135deg, #d4fc79 0%, #96e6a1 100%); }
	.type-medium { background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%); }
	.type-hard { background: linear-gradient(135deg, #ff7675 0%, #d63031 100%); }

	.diff-easy { background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%); }
	.diff-medium { background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%); }
	.diff-hard { background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%); }

	.type-text, .difficulty-text {
		font-size: 22rpx;
		font-weight: 700;
		color: white;
	}

	/**
	 * 题目标题
	 */
	.question-title {
		font-size: 34rpx;
		font-weight: 800;
		color: #1a202c;
		line-height: 1.7;
		display: block;
		margin-bottom: 28rpx;
		letter-spacing: 0.5rpx;
	}

	/**
	 * 代码块
	 */
	.code-block {
		background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		overflow-x: auto;
	}

	.code-text {
		font-family: 'SF Mono', 'Monaco', 'Consolas', 'Courier New', monospace;
		font-size: 24rpx;
		color: #e2e8f0;
		line-height: 1.8;
		white-space: pre-wrap;
	}

	/**
	 * 选项列表
	 */
	.options-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.option-item {
		display: flex;
		align-items: flex-start;
		gap: 16rpx;
		padding: 24rpx;
		background: linear-gradient(135deg, #f8f9fa 0%, #f1f5f9 100%);
		border: 3rpx solid transparent;
		border-radius: 16rpx;
		transition: all 0.3s ease;
		cursor: pointer;

		&:active {
			transform: scale(0.98);
		}
	}

	.option-selected {
		background: linear-gradient(135deg, #e8eaf6 0%, #d1d5f0 100%);
		border-color: #667eea;
		box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.2);
	}

	.option-radio {
		width: 40rpx;
		height: 40rpx;
		border: 3rpx solid #cbd5e1;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.option-selected .option-radio {
		border-color: #667eea;
		background: white;
	}

	.radio-inner {
		width: 24rpx;
		height: 24rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 50%;
	}

	.option-content {
		flex: 1;
		display: flex;
		gap: 8rpx;
	}

	.option-key {
		font-size: 28rpx;
		font-weight: 700;
		color: #667eea;
	}

	.option-text {
		font-size: 28rpx;
		color: #1a202c;
		line-height: 1.5;
	}

	/**
	 * 多选提示
	 */
	.multi-tip {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-top: 24rpx;
		padding: 16rpx;
		background: linear-gradient(135deg, #fff9e6 0%, #ffe9a0 100%);
		border-radius: 12rpx;
	}

	.tip-icon {
		font-size: 28rpx;
	}

	.tip-text {
		font-size: 24rpx;
		color: #d97706;
		font-weight: 600;
	}

	/**
	 * 查看答案区域
	 */
	.answer-section {
		margin-top: 32rpx;
		padding: 24rpx;
		background: white;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.view-answer-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #10b981 0%, #059669 100%);
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		border: none;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba(16, 185, 129, 0.4);
		}

		&.answer-expanded {
			background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
			box-shadow: 0 4rpx 12rpx rgba(245, 158, 11, 0.3);
		}
	}

	.btn-icon {
		font-size: 32rpx;
		color: white;
		font-weight: 700;
	}

	.btn-text {
		font-size: 32rpx;
		color: white;
		font-weight: 700;
	}

	.answer-content {
		margin-top: 24rpx;
		padding: 28rpx;
		background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
		border-radius: 16rpx;
		border-left: 6rpx solid #10b981;
		animation: slideDown 0.3s ease;
		box-shadow: 0 4rpx 16rpx rgba(16, 185, 129, 0.15);
	}

	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.answer-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 20rpx;
	}

	.answer-label {
		font-size: 28rpx;
		font-weight: 700;
		color: #059669;
	}

	.answer-options {
		display: flex;
		gap: 12rpx;
		flex-wrap: wrap;
	}

	.answer-key {
		min-width: 56rpx;
		height: 56rpx;
		background: linear-gradient(135deg, #10b981 0%, #059669 100%);
		color: white;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 700;
		box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
	}

	.explanation-item {
		margin-top: 24rpx;
		padding: 20rpx;
		background: white;
		border-radius: 12rpx;
		border-left: 4rpx solid #3b82f6;
	}

	.explanation-label {
		font-size: 28rpx;
		font-weight: 700;
		color: #3b82f6;
		display: block;
		margin-bottom: 12rpx;
	}

	.explanation-text {
		font-size: 28rpx;
		color: #1a202c;
		line-height: 1.8;
		display: block;
	}

	.code-example {
		margin-top: 24rpx;
		padding: 20rpx;
		background: #1e293b;
		border-radius: 12rpx;
	}

	.code-label {
		font-size: 28rpx;
		font-weight: 700;
		color: #60a5fa;
		display: block;
		margin-bottom: 12rpx;
	}

	.code-block {
		padding: 16rpx;
		background: #0f172a;
		border-radius: 8rpx;
		border-left: 4rpx solid #60a5fa;
	}

	.code-text {
		font-size: 24rpx;
		color: #e2e8f0;
		line-height: 1.8;
		font-family: 'Courier New', monospace;
		white-space: pre-wrap;
		word-break: break-all;
	}

	/**
	 * 底部操作栏
	 */
	.bottom-bar {
		flex-shrink: 0;
		padding: 24rpx 32rpx;
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		background: white;
		display: flex;
		gap: 20rpx;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
		position: relative;
		z-index: 10;
	}

	.nav-button {
		flex: 1;
		height: 88rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 700;
		border: none;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.97);
		}

		&[disabled] {
			opacity: 0.4;
		}
	}

	.prev-button {
		background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
		color: #475569;
	}

	.next-button {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
	}

	.submit-button {
		background: linear-gradient(135deg, #10b981 0%, #059669 100%);
		color: white;
		box-shadow: 0 8rpx 20rpx rgba(16, 185, 129, 0.4);
	}

	.button-text {
		color: inherit;
		font-size: inherit;
		font-weight: inherit;
	}
</style>

